<template>
  <div class="alarm-charts">
    <el-row :gutter="24">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span class="title">告警级别分布</span>
              <el-radio-group v-model="distributionTimeRange" size="small">
                <el-radio-button label="day">今日</el-radio-button>
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="pieChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span class="title">告警趋势（近7日）</span>
              <el-radio-group v-model="trendType" size="small">
                <el-radio-button label="all">全部</el-radio-button>
                <el-radio-button label="high">高危</el-radio-button>
                <el-radio-button label="medium">中危</el-radio-button>
                <el-radio-button label="low">低危</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="lineChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'
import type { EChartsOption } from 'echarts'
import { getAlarmDistribution, getAlarmTrend } from '../api/alarm'
import type { AlarmDistribution, AlarmTrend } from '../types/alarm'

const distributionTimeRange = ref('day')
const trendType = ref('all')
const pieChartRef = ref<HTMLElement>()
const lineChartRef = ref<HTMLElement>()
let pieChart: echarts.ECharts | null = null
let lineChart: echarts.ECharts | null = null

// 加载告警分布数据
const loadDistributionData = async () => {
  try {
    const data = await getAlarmDistribution()
    updatePieChart(data[distributionTimeRange.value])
  } catch (error) {
    console.error('Failed to load distribution data:', error)
  }
}

// 加载告警趋势数据
const loadTrendData = async () => {
  try {
    const data = await getAlarmTrend()
    updateLineChart(data)
  } catch (error) {
    console.error('Failed to load trend data:', error)
  }
}

// 更新饼图
const updatePieChart = (data: AlarmDistribution[]) => {
  if (!pieChart) return
  
  const option: EChartsOption = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: '5%',
      top: 'center'
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold'
          }
        },
        data,
        color: ['#F56C6C', '#E6A23C', '#67C23A']
      }
    ]
  }
  pieChart.setOption(option)
}

// 更新折线图
const updateLineChart = (data: AlarmTrend) => {
  if (!lineChart) return

  const option: EChartsOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['全部告警', '高危告警', '中危告警', '低危告警'],
      bottom: '0%'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: data.dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '全部告警',
        type: 'line',
        data: data[trendType.value],
        smooth: true,
        showSymbol: false,
        itemStyle: {
          color: '#409EFF'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(64,158,255,0.2)'
              },
              {
                offset: 1,
                color: 'rgba(64,158,255,0)'
              }
            ]
          }
        }
      }
    ]
  }
  lineChart.setOption(option)
}

// 初始化图表
const initCharts = () => {
  // 初始化饼图
  if (pieChartRef.value) {
    pieChart = echarts.init(pieChartRef.value)
  }
  
  // 初始化折线图
  if (lineChartRef.value) {
    lineChart = echarts.init(lineChartRef.value)
  }

  // 加载数据
  loadDistributionData()
  loadTrendData()
}

// 监听时间范围变化
watch(distributionTimeRange, () => {
  loadDistributionData()
})

// 监听趋势类型变化
watch(trendType, () => {
  loadTrendData()
})

// 监听窗口大小变化
const handleResize = () => {
  pieChart?.resize()
  lineChart?.resize()
}

onMounted(() => {
  initCharts()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  pieChart?.dispose()
  lineChart?.dispose()
})
</script>

<style scoped lang="scss">
.alarm-charts {
  margin-bottom: 24px;

  .chart-card {
    height: 400px;

    :deep(.el-card__header) {
      padding: 12px 20px;
      border-bottom: 1px solid #ebeef5;
    }

    .chart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .title {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }
    }

    .chart-container {
      height: 320px;
    }
  }
}
</style> 